package network;/*
 *@ 代阳敲的专属代码
 **/

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoServer {
    //定义个DatagramSocket的引用
    private DatagramSocket socket;
    public UdpEchoServer(int port) throws SocketException {
        //创建一个服务器，port指定端口
        this.socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务端已经启动");
        //循环24小时处理客户端消息
        while (true) {
            //定义打包数据
            DatagramPacket requestpacket=new DatagramPacket(new byte[1024],1024);
            //接收客户端数据
            socket.receive(requestpacket);

            //转化为String类型，这个只适合文本数据，不可以是图片数据，图片数据转化为二进制。
            String request=new String(requestpacket.getData(),0,
                    requestpacket.getLength(),"UTF-8");

            //处理数据，并把反馈数据赋给response
            String response=process(request);

            //重新打包数据
            DatagramPacket responedPacket =new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    0, response.getBytes().length,requestpacket.getSocketAddress());

            //发送给客户端
            socket.send(responedPacket);
            System.out.printf("[%s:%d] req: %s,resp: %s\n",requestpacket.getAddress().toString(),requestpacket.getPort(),request,response);
        }
    }
    //具体处理客户端数据的逻辑
    protected String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer=new UdpEchoServer(8080);
        udpEchoServer.start();
//        UdpEchoClient udpEchoClient=new UdpEchoClient("127.0.0.1",8080);
//        udpEchoClient.strat();
    }
}
